# coding:utf-8
# @Time : 2021/5/9 18:05 
# @Author : minuy
# @File : user.py
import re

from flask import request, url_for
from sqlalchemy.exc import IntegrityError

from app import login_auth, db

from app.api import api
from app.api.interface import api_result
from app.libs.file_tool import get_file_url
from app.libs.md5_tool import get_md5_value
from app.libs.verification_tool import is_http_url
from app.models.profile import Profile
from app.models.user import User


@api.route('/user_profile', methods=['POST'])
@login_auth.login_required
def user_get_profile():
    user = login_auth.current_user
    if user:
        profile = Profile.query.filter_by(user_id=user.id).first()
        if profile:

            birthday = profile.birthday
            if not birthday:
                birthday = ''
            else:
                birthday = birthday.strftime('%Y-%m-%d')

            user_profile = {
                'avatar': profile.avatar,
                'photo1': profile.photo1,
                'photo2': profile.photo2,
                'photo3': profile.photo3,
                'photo4': profile.photo4,
                'username': user.username,
                'nickname': user.nickname,
                'sex': user.sex,
                'region': profile.region,
                'birthday': birthday,
                'autograph': profile.signature
            }
            return api_result(data={
                'user_profile': user_profile
            })
    return api_result(code=403, message='未登录')


@api.route('/update_profile', methods=['POST'])
@login_auth.login_required
def user_update_profile():
    """
    主页点击我的请求的内容
    :return: config和user_data
    """
    user = login_auth.current_user
    print(user, '修改资料')
    user_profile = Profile.query.filter_by(user_id=user.id).first()
    print(user_profile)
    user_up_info = request.get_json()
    if user_profile and user and user_up_info:
        p1 = user_up_info.get('p1')
        p2 = user_up_info.get('p2')
        p3 = user_up_info.get('p3')
        p4 = user_up_info.get('p4')
        nickname = user_up_info.get('nickname')
        region = user_up_info.get('region')
        birthday = user_up_info.get('birthday')
        autograph = user_up_info.get('autograph')

        if p1 and \
                p2 and \
                p3 and \
                p4 and \
                nickname and \
                region and \
                birthday and \
                autograph:

            if not (p1 == '' or is_http_url(p1)):
                print('照片1 URL地址不正确', p1)
                return api_result(code=403, message='照片1 URL地址不正确')
            if not (p2 == '' or is_http_url(p2)):
                print('照片2 URL地址不正确', p2)
                return api_result(code=403, message='照片2 URL地址不正确')
            if not (p3 == '' or is_http_url(p3)):
                print('照片3 URL地址不正确', p3)
                return api_result(code=403, message='照片3 URL地址不正确')
            if not (p4 == '' or is_http_url(p4)):
                print('照片4 URL地址不正确', p4)
                return api_result(code=403, message='照片4 URL地址不正确')
            if not (len(nickname) < 9):
                print('昵称长度不正确', nickname)
                return api_result(code=403, message='昵称长度不正确')
            if not (len(region) < 100):
                print('地区长度不正确', nickname)
                return api_result(code=403, message='地区长度不正确')
            if not re.match(
                    r"^(?:(?!0000)[0-9]{4}-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])-(?:29|30)|(?:0[13578]|1[02])-31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)-02-29)$",
                    birthday):
                print('日期不正确', birthday)
                return api_result(code=403, message='日期不正确')
            if not (len(autograph) < 50):
                print('签名长度不正确', autograph)
                return api_result(code=403, message='签名长度不正确')

            user_profile.photo1 = p1
            user_profile.photo2 = p2
            user_profile.photo3 = p3
            user_profile.photo4 = p4
            user.nickname = nickname
            user_profile.region = region
            user_profile.birthday = birthday
            user_profile.signature = autograph

            try:
                db.session.commit()
                return api_result(code=200)
            except Exception as e:
                print('异常', e)
                return api_result(code=500, message='数据库错误')
    return api_result(code=403, message='参数不完整')


@api.route('/my')
@login_auth.login_required
def index_user_page():
    """
    主页点击我的请求的内容
    :return: config和user_data
    """
    user = login_auth.current_user
    print(user, '请求主页，我的')
    user_profile = Profile.query.filter_by(user_id=user.id).first()
    print(user_profile)
    if user_profile:
        return api_result(data={
            #  界面配置信息
            'config': {
                'order': True,  # 订单
                'wallet': True,  # 钱包
                'subscribe': True,  # 关注
                'follow': True,  # 粉丝
                'visitor': True,  # 访客
                'footprint': True,  # 足迹
                'appreciate': True,  # 赞赏
                'feedback': True,  # 反馈
                'apply': True,  # 申请
                'setting': True,  # 设置
                'about': True  # 关于
            },
            'user_data': {
                'avatar_src': user_profile.avatar,
                'nick': user.nickname
            }
        })
    return api_result(message='服务器错误', data={
        #  界面配置信息
        'config': {
            'order': False,  # 订单
            'wallet': False,  # 钱包
            'subscribe': False,  # 关注
            'follow': False,  # 粉丝
            'visitor': False,  # 访客
            'footprint': False,  # 足迹
            'appreciate': False,  # 赞赏
            'feedback': False,  # 反馈
            'apply': False,  # 申请
            'setting': False,  # 设置
            'about': False  # 关于
        },
        'user_data': {
            'avatar_src': '',
            'nick': '出错'
        }
    })


@api.route('/register', methods=['POST'])
def register_user():
    """
    注册用户
    :return: 注册结果，成功、失败
    """
    user_register_info = request.get_json()
    print(user_register_info)
    if user_register_info:
        phone = user_register_info.get('phone')  # 手机
        code = user_register_info.get('code')  # 验证码
        s_code = user_register_info.get('s_code')  # 服务器下发的验证码
        password = user_register_info.get('password')  # 密码
        nick = user_register_info.get('nick')  # 昵称
        sex = user_register_info.get('sex')  # 性别

        if phone and \
                code and \
                s_code and \
                password and \
                nick and \
                sex:
            if not re.match(r"^1[35678]\d{9}$", phone):
                print('手机号不正确', phone)
                return api_result(code=403, message='手机号不正确')
            if not (re.match(r"^\d{6}$", code) and (get_md5_value(code) == s_code)):
                print('验证码不正确', code, s_code)
                return api_result(code=403, message='验证码不正确')
            if not re.match(r"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]+\S{5,12}$", password):
                print('密码不符合要求', password)
                return api_result(code=403, message='密码不符合要求')
            if not (8 >= len(nick) >= 1):
                print('昵称不符合要求', nick)
                return api_result(code=403, message='昵称不符合要求')
            if not ((len(sex) == 1) and (sex == '男' or sex == '女')):
                print('性别格式错误', sex)
                return api_result(code=403, message='性别格式错误')

            # 完成数据校验
            try:
                print('完成数据校验')
                # user_info = User(username=phone, password=password, nickname=nick, sex=sex)
                user_info = User(username=phone, password=password, nickname=nick, sex=sex)
                db.session.add(user_info)
                db.session.commit()
            except Exception as e:
                print(e)
                return api_result(code=500, message='用户已经注册')

            user_info = User.query.filter_by(username=phone).first()
            user_profile = Profile(user_id=user_info.id, phone=phone, avatar=get_file_url('avatar.png'))
            db.session.add(user_profile)
            db.session.commit()

            return api_result(code=200, message='注册成功')
    return api_result(code=403, message='参数不完整')
